package org.chen.controller;

import org.chen.model.admin.SysUser;
import org.chen.model.dto.LoginDTO;
import org.chen.model.dto.UpdatePasswordDTO;
import org.chen.model.dto.UpdateProfileDTO;
import org.chen.response.Result;
import org.chen.service.impl.SysUserServiceImpl;
import org.chen.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private SysUserServiceImpl userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO loginDTO) {
        String token = userService.login(loginDTO.getUsername(), loginDTO.getPassword());
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        return Result.success(tokenMap);
    }

    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        String authHeader = request.getHeader(tokenHeader);
        if (authHeader != null && authHeader.startsWith(tokenHead)) {
            String authToken = authHeader.substring(tokenHead.length()).trim();
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            if (username != null) {
                userService.logout(username);
            }
        }
        return Result.success();
    }

    @GetMapping("/user-info")
    public Result getUserInfo(Principal principal) {
        System.out.println(principal);
        String username = principal.getName();
        SysUser user = (SysUser) userService.loadUserByUsername(username);
        Map<String, Object> data = new HashMap<>();
        data.put("username", user.getUsername());
        data.put("nickname", user.getNickname());
        data.put("email", user.getEmail());
        data.put("avatar", user.getAvatar());
        data.put("roles", user.getRoles());
        return Result.success(data);
    }

    @PutMapping("/profile")
    public Result updateProfile(@RequestBody UpdateProfileDTO profileDTO) {
        userService.updateProfile(profileDTO);
        return Result.success();
    }

    @PutMapping("/password")
    public Result updatePassword(@RequestBody UpdatePasswordDTO passwordDTO) {
        userService.updatePassword(passwordDTO);
        return Result.success();
    }
}
